App 不只是被動等使用者打開,有時候我們希望主動提醒使用者有新內容或事件,這就是 Push Notification(推播通知) 的任務。
今天我們就要來介紹 iOS 的通知機制,包含:
推播通知是 App 與使用者之間的溝通橋樑,用途包含:
在 iOS 中主要分成兩種
要使用通知,第一步就是向使用者申請授權。
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]){ granted, error in
if granted {
print("使用者允許通知")
} else {
print("使用者拒絕通知")
}
}
例如:3 秒後顯示一則通知。
func sendLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "提醒你一下 📣"
content.body = "該回來繼續學 Swift 鐵人賽囉!"
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let request = UNNotificationRequest(identifier: "SwiftDay20", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
預設情況下,App 在前景時不會顯示通知。
要讓通知在前景時也能彈出,我們可以實作 delegate:
import SwiftUI
import UserNotifications
class NotificationManager: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
override init() {
super.init()
// 註冊通知權限
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("使用者允許通知")
} else {
print("使用者拒絕通知")
}
}
// 指定 delegate
UNUserNotificationCenter.current().delegate = self
}
// 實作前景通知顯示
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// App 在前景時也顯示通知
completionHandler([.banner, .sound])
}
// 發送通知
func sendLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "提醒你一下"
content.body = "該回來繼續學 Swift 鐵人賽囉!"
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let request = UNNotificationRequest(identifier: "SwiftDay20", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
}
由於沒有 Apple Developer 帳號,我們先簡單介紹原理。
APNs(Apple Push Notification Service) 是 Apple 官方的推播服務平台。所有發送到 iPhone、iPad、Mac 的推播,都必須經過 APNs。
Remote Notification的流程如下:
你的伺服器 → APNs → 使用者的 iPhone → 顯示通知
(你的伺服器端就能用這個 Token 發送推播)
今天我們學到: